﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Runtime.Remoting.Contexts;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using 基于Winform的HTTP服务端.Models;

namespace 基于Winform的HTTP服务端
{
    public partial class Form1 : Form
    {
        private HttpListener httpListener;
        private const string AreYouThereUrl = "http://localhost:8080/restApi/AreYouThere/";
        private const string EQPStatusChangeReportUrl = "http://localhost:8080/restApi/EQPStatusChangeReport/";
        public Form1()
        {
            InitializeComponent();
            httpListener = new HttpListener();
            httpListener.Prefixes.Add(AreYouThereUrl);
            httpListener.Prefixes.Add(EQPStatusChangeReportUrl);
        }

        private void button1_Click(object sender, EventArgs e)
        {
            StartServer();
        }
        private async void StartServer()
        {
            try
            {
                httpListener.Start();
                UpdateLog("Server started at " + AreYouThereUrl);
                UpdateLog("Server started at " + EQPStatusChangeReportUrl);
                await ListenForRequests();
            }
            catch (Exception ex)
            {
                UpdateLog("Error: " + ex.Message);
            }
        }
        private async Task ListenForRequests()
        {
            while (true)
            {
                try
                {
                    var context = await httpListener.GetContextAsync(); // 获取 HTTP 请求
                    ProcessRequest(context); // 处理请求
                }
                catch (Exception ex)
                {
                    UpdateLog("Request error: " + ex.Message);
                }
            }
        }

        private void ProcessRequest(HttpListenerContext context)
        {
            string responseString = string.Empty;
            var header = context.Request.Headers.GetValues("Basic_base64_auth_string");//检验base64
            var contentType = context.Request.Headers.GetValues("Content-Type");//Content-Type
            var eqpId = context.Request.Headers.GetValues("EqpId");//EqpId
            var url = context.Request.RawUrl;
            if (header is null || contentType is null || eqpId is null)
            {
                // 设置响应内容
                context.Response.StatusCode = (int)HttpStatusCode.OK;
                byte[] buffer = Encoding.UTF8.GetBytes("错误");
                context.Response.ContentLength64 = buffer.Length;
                using (var output = context.Response.OutputStream)
                {
                    output.Write(buffer, 0, buffer.Length);
                }
                return;
            }
            if (context.Request.HttpMethod == "POST")
            {
                if (url == "/restApi/AreYouThere/")
                {
                    using (var reader = new StreamReader(context.Request.InputStream, context.Request.ContentEncoding))
                    {
                        var requestBody = reader.ReadToEnd();
                        AreYouThereModel.Rootobject arede=JsonConvert.DeserializeObject<AreYouThereModel.Rootobject>(requestBody);//解析

                        AreYouThereModel.Rootobject areYouthere = new AreYouThereModel.Rootobject()
                        {
                            Header = new AreYouThereModel.Header()
                            {
                                MessageName = "",
                                TransactionID = "",
                                UserID = ""
                            },
                            Body = new AreYouThereModel.Body() { EquipmentID = "" },
                            Result = new AreYouThereModel.Result()
                            {
                                Code = 200,
                                MessageCH = "",
                                MessageEN = ""
                            }
                        };
                        responseString = JsonConvert.SerializeObject(areYouthere);
                        UpdateLog($"Request received: {responseString}");
                    }
                    // 设置响应内容
                    context.Response.StatusCode = (int)HttpStatusCode.OK;
                    byte[] buffer = Encoding.UTF8.GetBytes(responseString);
                    context.Response.ContentLength64 = buffer.Length;
                    using (var output = context.Response.OutputStream)
                    {
                        output.Write(buffer, 0, buffer.Length);
                    }
                }
                if (url == "/restApi/EQPStatusChangeReport/")
                {
                    using (var reader = new StreamReader(context.Request.InputStream, context.Request.ContentEncoding))
                    {
                        var requestBody = reader.ReadToEnd();
                        EQPStatusChangeReportModel.Rootobject areYouthere = new EQPStatusChangeReportModel.Rootobject()
                        {
                            Header = new EQPStatusChangeReportModel.Header()
                            {
                                MessageName = "",
                                TransactionID = "",
                                UserID = ""
                            },
                            Body = new EQPStatusChangeReportModel.Body()
                            {
                                EquipmentID = "",
                                Status = ""
                            },
                            Result = new EQPStatusChangeReportModel.Result()
                            {
                                Code = 200,
                                MessageCH = "",
                                MessageEN = ""
                            }
                        };
                        responseString = JsonConvert.SerializeObject(areYouthere);
                        UpdateLog($"Request received: {responseString}");
                    }
                    // 设置响应内容
                    context.Response.StatusCode = (int)HttpStatusCode.OK;
                    byte[] buffer = Encoding.UTF8.GetBytes(responseString);
                    context.Response.ContentLength64 = buffer.Length;
                    using (var output = context.Response.OutputStream)
                    {
                        output.Write(buffer, 0, buffer.Length);
                    }
                }

            }
            else
            {
                context.Response.StatusCode = (int)HttpStatusCode.MethodNotAllowed;
                UpdateLog("Method not allowed: " + context.Request.HttpMethod);
            }

            context.Response.Close();
        }

        private void UpdateLog(string message)
        {
            if (InvokeRequired)
            {
                Invoke(new Action<string>(UpdateLog), message);
                return;
            }

            textBox1.AppendText(message + Environment.NewLine);
            textBox1.ScrollToCaret();
        }

        protected override void OnFormClosing(FormClosingEventArgs e)
        {
            base.OnFormClosing(e);
            if (httpListener.IsListening)
            {
                httpListener.Stop(); // 停止监听
            }
        }

        private async void button2_Click(object sender, EventArgs e)
        {
            HttpClient httpClient = new HttpClient();
            httpClient.DefaultRequestHeaders.Add("Basic_base64_auth_string", "Basic");
            httpClient.DefaultRequestHeaders.Add("EqpId", "EqpId");
            if (textBox3.Text.Contains("/restApi/EQPStatusChangeReport/"))
            {
                EQPStatusChangeReportModel.Rootobject areYouthere = new EQPStatusChangeReportModel.Rootobject()
                {
                    Header = new EQPStatusChangeReportModel.Header()
                    {
                        MessageName = "",
                        TransactionID = "",
                        UserID = ""
                    },
                    Body = new EQPStatusChangeReportModel.Body()
                    {
                        EquipmentID = "",
                        Status = ""
                    },
                    Result = new EQPStatusChangeReportModel.Result()
                    {
                        Code = 200,
                        MessageCH = "",
                        MessageEN = ""
                    }
                };
              textBox2.Text=  await (await httpClient.PostAsync(textBox3.Text, new StringContent(JsonConvert.SerializeObject(areYouthere),Encoding.UTF8,"application/json"))).Content.ReadAsStringAsync();
            }
            if (textBox3.Text.Contains("/restApi/AreYouThere/"))
            {
                AreYouThereModel.Rootobject areYouthere = new AreYouThereModel.Rootobject()
                {
                    Header = new AreYouThereModel.Header()
                    {
                        MessageName = "",
                        TransactionID = "",
                        UserID = ""
                    },
                    Body = new AreYouThereModel.Body() { EquipmentID = "" },
                    Result = new AreYouThereModel.Result()
                    {
                        Code = 200,
                        MessageCH = "",
                        MessageEN = ""
                    }
                };
                textBox2.Text = await (await httpClient.PostAsync(textBox3.Text, new StringContent(JsonConvert.SerializeObject(areYouthere), Encoding.UTF8, "application/json"))).Content.ReadAsStringAsync();
            }
        }
    }
}
